package com.magicsoft.weitown.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.bitmap.mysqlite.BitmapHelper;
import com.boyuan.aboutcase.MySwipeMenuListView;
import com.boyuan.huijiaoyu.HomeContactDeail2Activity;
import com.boyuan.huijiaoyu.R;
import com.boyuan.huijiaoyu.SelectFriendFromContactsActivity;
import com.boyuan.huijiaoyu.SwipeListViewForScrollView;
import com.example.contactfragment.ContactService;
import com.example.contactfragment.HomeContactAdapter;
import com.example.contactfragment.HomeContactAdapter.IOnItemRightClickListener;
import com.example.contactfragment.HomeContactMyCaseGroupActivity;
import com.example.contactfragment.HomeContactMyGroupActivity;
import com.example.contactfragment.HomeContactOrgActivity;
import com.example.contactfragment.HomeContactSearchActivity;
import com.example.contactfragment.MyGroup;
import com.example.newfragment.DetailPerson;
import com.example.newfragment.HomeContactAdapter1;
import com.example.newfragment.HomeService;
import com.example.newfragment.RecentPerson;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.listener.GetOneRecordListener;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;
import com.magicsoft.weitown.ui.SwipeListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 通讯录
 * 
 * @author liqingjun
 * 
 */
public class HomeContactFragment extends BaseFragment implements
		OnClickListener {
	private final static String TAG = "HomeContactFragment";
	private final static int INTENT_ACTION_OPEN_DETAIL = 1;
	private final static int INTENT_ACTION_OPEN_ORG = 2;
	// 搜索
	private LinearLayout lin_search;
	// 组织架构
	private RelativeLayout rl_structure;
	//
	private TextView tv_structure;
	// 我的部门
	private RelativeLayout rl_my_department;
	//
	private TextView tv_my_department;
	// 手机通讯录
	private RelativeLayout rl_mobile_contact;
	// 我的群组
	private RelativeLayout rl_my_group;
	// 星标联系人
	private TextView tv_xingbiao_contact;
	//常用联系人
	private TextView tv_common_contact;
	private ArrayList<DetailPerson> datas = new ArrayList<DetailPerson>();
	private ArrayList<DetailPerson> datas01 = new ArrayList<DetailPerson>();
	private ArrayList<DetailPerson> datas02 = new ArrayList<DetailPerson>();
	private ArrayList<DetailPerson> datas2 = new ArrayList<DetailPerson>();
	private DetailPerson homeContactCommonEntity;
	private ContactService contactService;
	private RecentPerson rootContactOrg;
	boolean isreqchangyong = false;
	boolean isreqxingbiao = false;
	private DisplayImageOptions options;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.home_contact_fragment, null);
		sp1 = getActivity().getSharedPreferences("a.xml", 0);
		bumen = sp1.getString("familyname", "");
		id = sp1.getString("id", "");
		imageLoader.clearMemoryCache();
		imageLoader.clearDiscCache();
		prepareView(view);
		registerLoginReceiver();
		registChangyongRecive();
		registShanChangyongRecive();
		registAddXingbiaoRecive();
		registShanchuXingbiaoRecive();
		return view;
	}

	public void registerLoginReceiver() {
		myFirstChangeHeadIcon = new MyFirstChangeHeadIcon();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.FirstChangePersonHeadIcon);
		getActivity().registerReceiver(myFirstChangeHeadIcon, filter);
	}

	class MyFirstChangeHeadIcon extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			bumen = sp1.getString("familyname", "");
			tv_my_department.setText(bumen);
		}

	}

	public void registShanchuXingbiaoRecive() {
		shanchuXingbiaoRecive = new ShanchuXingbiaoRecive();
		IntentFilter filter = new IntentFilter();
		filter.addAction("ShanchuXingbiao");
		getActivity().registerReceiver(shanchuXingbiaoRecive, filter);
	}

	class ShanchuXingbiaoRecive extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			getFrequentContactCache();
//			getXingbiaoContactCache();
			getFrequentContacts();
//			getXingbiaoContacts();
		}

	}

	public void registAddXingbiaoRecive() {
		addXingbiaoRecive = new AddXingbiaoRecive();
		IntentFilter filter = new IntentFilter();
		filter.addAction("AddXingbiao");
		getActivity().registerReceiver(addXingbiaoRecive, filter);
	}

	class AddXingbiaoRecive extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			getFrequentContactCache();
//			getXingbiaoContactCache();
			getFrequentContacts();
//			getXingbiaoContacts();
		}

	}

	public void registChangyongRecive() {
		changyongRecive = new ChangyongRecive();
		IntentFilter filter = new IntentFilter();
		filter.addAction("Changyong");
		getActivity().registerReceiver(changyongRecive, filter);
	}

	class ChangyongRecive extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			getFrequentContactCache();
//			getXingbiaoContactCache();
			getFrequentContacts();
//			getXingbiaoContacts();
		}
	}

	public void registShanChangyongRecive() {
		shanchuchangyongRecive = new ShanchuChangyongRecive();
		IntentFilter filter = new IntentFilter();
		filter.addAction("ShanchuChangyong");
		getActivity().registerReceiver(shanchuchangyongRecive, filter);
	}

	class ShanchuChangyongRecive extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			getFrequentContactCache();
//			getXingbiaoContactCache();
			getFrequentContacts();
//			getXingbiaoContacts();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(changyongRecive);
		getActivity().unregisterReceiver(shanchuchangyongRecive);
		getActivity().unregisterReceiver(addXingbiaoRecive);
		getActivity().unregisterReceiver(shanchuXingbiaoRecive);
		getActivity().unregisterReceiver(myFirstChangeHeadIcon);
	}

	private void prepareView(View view) {

		View headerView = LayoutInflater.from(getActivity()).inflate(
				R.layout.home_contact_header, null);
		// 搜索

		lin_search = (LinearLayout) headerView.findViewById(R.id.lin_search);
		lin_search.setOnClickListener(this);
		// 组织架构
		rl_structure = (RelativeLayout) headerView
				.findViewById(R.id.rl_structure);
		rl_structure.setOnClickListener(this);
		tv_structure = (TextView) headerView.findViewById(R.id.tv_structure);
		// 我的部门
		rl_my_department = (RelativeLayout) headerView
				.findViewById(R.id.rl_my_department);
		rl_my_department.setOnClickListener(this);
		tv_my_department = (TextView) headerView
				.findViewById(R.id.tv_my_department);
		tv_my_department.setText(bumen);
		// 手机通讯录
		rl_mobile_contact = (RelativeLayout) headerView
				.findViewById(R.id.rl_mobile_contact);
		rl_mobile_contact.setOnClickListener(this);
		// 我的群组
		rl_my_group = (RelativeLayout) headerView
				.findViewById(R.id.rl_my_group);
		rl_my_group.setOnClickListener(this);
		//我的case群组
		rl_my_casegroup = (RelativeLayout) headerView.findViewById(R.id.rl_my_casegroup);
		rl_my_casegroup.setOnClickListener(this);
		//星标联系人
		tv_xingbiao_contact = (TextView) headerView.findViewById(R.id.tv_xingbiao_contact);
		tv_xingbiao_contact.setVisibility(View.GONE);
		
		listxingbiao = (MySwipeMenuListView) view.findViewById(R.id.listView_xingbiao);
		// 屏蔽掉headerview
//		listxingbiao.setHeaderViewCanSwipe(false);
//		View footview = LayoutInflater.from(getActivity()).inflate(R.layout.list_foot, null);
//		//常用联系人
//		tv_common_contact = (TextView) footview.findViewById(R.id.tv_com);
//		MySwipeMenuListView listfoot = (MySwipeMenuListView) footview.findViewById(R.id.listView_changyong);
//		adapter2 = new HomeContactAdapter1(getActivity(), datas, options, imageLoader);
//		listfoot.setAdapter(adapter2);
//		listfoot.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
//					long arg3) {
//				if(datas.size() > 0){
//					DetailPerson contactEntity1 = (DetailPerson) datas.get(arg2);
//					Intent intent = new Intent(getActivity(),
//							HomeContactDeail2Activity.class);
//					intent.putExtra("uid", contactEntity1.getUid());
//					intent.putExtra("titleback", "通讯录");
//					startActivity(intent);
//				}
//			}
//		});
//		
//		SwipeMenuCreator creator = new SwipeMenuCreator() {
//			@Override
//			public void create(SwipeMenu menu) {
//				SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity()
//						.getApplicationContext());
//				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
//						0x3F, 0x25)));
//				deleteItem.setWidth(dp2px(70));
//				deleteItem.setTitle("删除");
//				deleteItem.setTitleSize(12);
//				deleteItem.setTitleColor(Color.WHITE);
//				menu.addMenuItem(deleteItem);
//			}
//		};
//
//		listfoot.setMenuCreator(creator);
//		
//		listfoot.setOnMenuItemClickListener(new OnMenuItemClickListener() {
//			
//			@Override
//			public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
//				switch (index) {
//				case 0:
//					DetailPerson homeContactCommonEntity = (DetailPerson) datas.get(position);
//					deleteFrequentContacts(position, homeContactCommonEntity.getUid());
//				break;
//				}
//				return true;
//			}
//		});
//		listxingbiao.addHeaderView(headerView);
		listxingbiao.setHeaderDividersEnabled(false);
		listxingbiao.addHeaderView(headerView, null, false);
//		listxingbiao.addFooterView(footview);
		adapter1 = new HomeContactAdapter1(getActivity(), datas, options, imageLoader);
		listxingbiao.setAdapter(adapter1);
		listxingbiao.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if(datas.size()>0){
					if(arg2>0){
						DetailPerson contactEntity = (DetailPerson) datas.get(arg2 - 1);
						Intent intent = new Intent(getActivity(),
								HomeContactDeail2Activity.class);
						intent.putExtra("uid", contactEntity.getUid());
						intent.putExtra("homeContactDetailEntity", contactEntity);
						intent.putExtra("titleback", "通讯录");
						startActivity(intent);
					}else{
						
					}
				}
			}
		});
		
		SwipeMenuCreator creator1 = new SwipeMenuCreator() {
			@Override
			public void create(SwipeMenu menu) {
				SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity()
						.getApplicationContext());
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				deleteItem.setWidth(dp2px(70));
				deleteItem.setTitle("删除");
				deleteItem.setTitleSize(12);
				deleteItem.setTitleColor(Color.WHITE);
				menu.addMenuItem(deleteItem);
			}
		};
		
		listxingbiao.setMenuCreator(creator1);
		listxingbiao.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			
			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
				switch (index) {
				case 0:
					DetailPerson homeContactCommonEntity = (DetailPerson) datas.get(position);
//					deleteXingbiaoContacts(position,homeContactCommonEntity.getUid());
					deleteFrequentContacts(position, homeContactCommonEntity.getUid());
				break;
				}
				return true;
			}
		});

	}

	// 测试
	private boolean isBackAllowed;
	private boolean progressShow;
	private String id;
	private View view;
	private ChangyongRecive changyongRecive;
	private ShanchuChangyongRecive shanchuchangyongRecive;
	private String bumen;
	private SharedPreferences sp1;
	private MyFirstChangeHeadIcon myFirstChangeHeadIcon;
	private AddXingbiaoRecive addXingbiaoRecive;
	private ShanchuXingbiaoRecive shanchuXingbiaoRecive;
	private RelativeLayout rl_my_casegroup;
	private HomeContactAdapter1 adapter2;
	private MySwipeMenuListView listxingbiao;
	private HomeContactAdapter1 adapter1;

	public void prepareData() {

		if (getActivity() == null) {
			return;
		}
		getOrgChildDatas();
		// 获得常用联系人
		getFrequentContactCache();
//		getXingbiaoContactCache();
		getActivity().runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				getFrequentContacts();
//				getXingbiaoContacts();
			}
		});
	}
	
	//获取常用联系人缓存
	private void getFrequentContactCache() {
		datas.clear();
		datas01.clear();
		datas02.clear();
		ArrayList<DetailPerson> frequentContactList = SharePreferenceHelper
				.getContactFrindList(getActivity(), id);
		if (frequentContactList.size() > 0) {
			tv_xingbiao_contact.setVisibility(View.VISIBLE);
			for (int i = 0; i < frequentContactList.size(); i++) {
				String is_favorite = frequentContactList.get(i).getIs_favorite();
				if("1".equals(is_favorite)){
					datas01.add(frequentContactList.get(i));
				}else{
					datas02.add(frequentContactList.get(i));
				}
			}
			datas.addAll(datas01);
			datas.addAll(datas02);
//			datas.addAll(frequentContactList);
//			adapter2.notifyDataSetChanged();
			adapter1.notifyDataSetChanged();
		}else{
			tv_xingbiao_contact.setVisibility(View.GONE);
		}
	}

	/**
	 * 获取常用联系人
	 */
	private void getFrequentContacts() {

		if (contactService == null) {
			contactService = new ContactService(getActivity());
		}
		contactService.getFrequentContacts(id,
				new GetOneRecordListener<List<DetailPerson>>() {

					@Override
					public void onFinish(List<DetailPerson> data) {
						datas.clear();
						datas01.clear();
						datas02.clear();
						if (data != null && data.size() > 0) {
//							datas.addAll(data);
							
							for (int i = 0; i < data.size(); i++) {
								String is_favorite = data.get(i).getIs_favorite();
								if("1".equals(is_favorite)){
									datas01.add(data.get(i));
								}else{
									datas02.add(data.get(i));
								}
							}
							datas.addAll(datas01);
							datas.addAll(datas02);
							SharePreferenceHelper.saveContactFrindList(getActivity(), id, datas);
							tv_xingbiao_contact.setVisibility(View.VISIBLE);
						}else{
							tv_xingbiao_contact.setVisibility(View.GONE);
						}
//						adapter2.notifyDataSetChanged();
						adapter1.notifyDataSetChanged();
						isreqchangyong = true;
					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(getActivity(), Message, false);
					}
				});
	}

	/**
	 * 删除常用联系人
	 */
	private void deleteFrequentContacts(final int position, String contactsId) {

		if (contactService == null) {
			contactService = new ContactService(getActivity());
		}

		contactService.deleteFrequentContact(id, contactsId,
				new GetOneRecordListener<String>() {

					@Override
					public void onFinish(String data) {
						datas.remove(position);
						if(datas.size()<=0){
							tv_xingbiao_contact.setVisibility(View.GONE);
						}else{
							tv_xingbiao_contact.setVisibility(View.VISIBLE);
						}
						adapter1.notifyDataSetChanged();
						getFrequentContacts();
						ToastHelper.showMsg(getActivity(), data, false);
					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(getActivity(), Message, false);
					}
				});
	}
	
	
	//获取星标联系人缓存
		private void getXingbiaoContactCache() {
			datas2.clear();
			ArrayList<DetailPerson> xingbiaoContactList = SharePreferenceHelper
					.getXingbiaoFrindList(getActivity(), id);
			if (xingbiaoContactList.size() > 0) {
				tv_xingbiao_contact.setVisibility(View.VISIBLE);
				datas2.addAll(xingbiaoContactList);
				adapter1.notifyDataSetChanged();
			}else{
				tv_xingbiao_contact.setVisibility(View.GONE);
			}
		}

	/**
	 * 获取星标联系人
	 */
	private void getXingbiaoContacts() {

		if (contactService == null) {
			contactService = new ContactService(getActivity());
		}
		contactService.getXingbiaoContacts(id,
				new GetOneRecordListener<List<DetailPerson>>() {

					@Override
					public void onFinish(List<DetailPerson> data) {
						datas2.clear();
						if (data != null && data.size() > 0) {
							datas2.addAll(data);
							SharePreferenceHelper.saveXingbiaoFrindList(getActivity(), id, data);
							tv_xingbiao_contact.setVisibility(View.VISIBLE);
						}else{
							tv_xingbiao_contact.setVisibility(View.GONE);
						}
						adapter1.notifyDataSetChanged();
						isreqxingbiao = true;
					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(getActivity(), Message, false);
					}
				});
	}

	/**
	 * 删除星标联系人
	 */
	private void deleteXingbiaoContacts(final int position, String contactsId) {

		if (contactService == null) {
			contactService = new ContactService(getActivity());
		}

		contactService.deleteContactFavorite(id, contactsId,
				new GetOneRecordListener<String>() {

					@Override
					public void onFinish(String data) {
						datas2.remove(position);
						if (datas2.size() > 0) {
							tv_xingbiao_contact.setVisibility(View.VISIBLE);
						}else{
							tv_xingbiao_contact.setVisibility(View.GONE);
						}
						adapter1.notifyDataSetChanged();
						ToastHelper.showMsg(getActivity(), data, false);
					}

					@Override
					public void onFailed(String Message) {
						ToastHelper.showMsg(getActivity(), Message, false);
					}
				});
	}

	/**
	 * 获取根目录
	 */
	private void getOrgChildDatas() {

		if (contactService == null) {
			contactService = new ContactService(getActivity());
		}

		contactService.getOrgChildDatas("0",
				new GetOneRecordListener<List<RecentPerson>>() {

					@Override
					public void onFinish(List<RecentPerson> data) {
						if (data != null && data.size() > 0) {
							rootContactOrg = data.get(0);
							tv_structure.setText(rootContactOrg.getName());
						}
					}

					@Override
					public void onFailed(String Message) {

					}
				});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.lin_search:
			// 搜索
			Intent searchIntent = new Intent(getActivity(),
					HomeContactSearchActivity.class);
			searchIntent.putExtra("isOnlyShowHistory", false);
			startActivity(searchIntent);
			break;
		case R.id.rl_structure:
			// 组织架构
			if (rootContactOrg != null) {
				Intent orgIntent = new Intent(getActivity(),
						HomeContactOrgActivity.class);
				RecentPerson homeContactOrgEntity = new RecentPerson();
				homeContactOrgEntity.setUid(rootContactOrg.getUid());
				homeContactOrgEntity.setName(rootContactOrg.getName());
				homeContactOrgEntity.setType("org");
				orgIntent.putExtra("homeContactOrgEntity", homeContactOrgEntity);
				startActivityForResult(orgIntent, INTENT_ACTION_OPEN_ORG);
			}
			break;
		case R.id.rl_my_department:
			// 我的部门
			SharedPreferences sp = getActivity().getSharedPreferences("a.xml",
					0);
			String familyid = sp.getString("familyid", "");
			String familyname = sp.getString("familyname", "");
			Intent departmentIntent = new Intent(getActivity(),
					HomeContactOrgActivity.class);
			RecentPerson homeContactOrgEntity = new RecentPerson();
			homeContactOrgEntity.setUid(familyid);
			homeContactOrgEntity.setName(familyname);
			homeContactOrgEntity.setType("org");
			departmentIntent.putExtra("homeContactOrgEntity", homeContactOrgEntity);
			startActivityForResult(departmentIntent, INTENT_ACTION_OPEN_ORG);
			break;
		case R.id.rl_mobile_contact:
//			// 手机通讯录
//			Intent contactIntent = new Intent(getActivity(),
//					SelectFriendFromContactsActivity.class);
//			startActivity(contactIntent);
//			break;
		case R.id.rl_my_group:
			// 我的群组
			Intent myGroupIntent = new Intent(getActivity(),
					HomeContactMyGroupActivity.class);
			myGroupIntent.putExtra("title", "我的群组");
			startActivity(myGroupIntent);
			break;
		case R.id.rl_my_casegroup:
			Intent myCaseGroupIntent = new Intent(getActivity(),
					HomeContactMyCaseGroupActivity.class);
			myCaseGroupIntent.putExtra("title", "我的运维申请");
			startActivity(myCaseGroupIntent);
			break;
		default:
			break;
		}

	}
	
	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		// 处理登录
		if (requestCode == INTENT_ACTION_OPEN_DETAIL
				|| requestCode == INTENT_ACTION_OPEN_ORG) {
			if (resultCode == Activity.RESULT_OK) {
				// getFrequentContacts();
			}
		}

		super.onActivityResult(requestCode, resultCode, data);

	}

}
